package com.mudu.search.service;

import com.mudu.search.entity.DimIndustry;
import com.mudu.search.entity.DimIndustryIndex;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * DimIndustry索引服务类
 *
 * @author lzqing
 * @since 2023-10-20 13:30
 */
@Service
public class DimIndustryIndexService {

    private static final Logger log = LoggerFactory.getLogger(DimIndustryIndexService.class);

    @Resource
    private DimIndustryService dimIndustryService;

    @Resource
    private ElasticsearchTemplate template;

    /**
     * 初始化索引结构和数据
     */
    public void initIndex() {
        // 处理索引结构
        IndexOperations indexOps = template.indexOps(DimIndustryIndex.class);
        if (indexOps.exists()) {
            boolean delFlag = indexOps.delete();
            log.info("dim_industry_index exists，delete:{}", delFlag);
            indexOps.createMapping(DimIndustryIndex.class);
        } else {
            log.info("dim_industry_index not exists");
            indexOps.createMapping(DimIndustryIndex.class);
        }
        // 同步数据库表记录
        List<DimIndustry> contentsList = dimIndustryService.queryAll();
        if (contentsList.size() > 0) {
            List<DimIndustryIndex> contentsIndexList = new ArrayList<>();
            contentsList.forEach(contents -> {
                DimIndustryIndex contentsIndex = new DimIndustryIndex();
                BeanUtils.copyProperties(contents, contentsIndex);
                contentsIndexList.add(contentsIndex);
            });
            template.save(contentsIndexList);
        }
        // ID查询
        DimIndustryIndex contentsIndex = template.get("10", DimIndustryIndex.class);
        log.info("dim_industry_index-10:{}", contentsIndex);
    }

}
